import { defineStore } from 'pinia';
import { createNotice, getNoticeDetail, updateNoticeById, deleteNoticeById } from '../../api/notice';
import type { NoticeInsertVO } from '../../api/notice/types';
import type { AxiosError } from 'axios';

type NoticeUpdateVO = NoticeInsertVO & { announId: number };

export const useNoticeStore = defineStore('notice', {
  state: () => ({
    currentNoticeId: null as number | null
  }),
  actions: {
    setCurrentNoticeId(id: number | null) {
      this.currentNoticeId = id;
    },
    async createNotice(notice: NoticeInsertVO) {
      console.log('Creating notice with data:', notice);
      try {
        return await createNotice(notice);
      } catch (error) {
        console.error('Error creating notice:', error);
        throw error;
      }
    },
    async getNoticeDetail(noticeId: number) {
      return await getNoticeDetail(noticeId);
    },
    async updateNotice(notice: NoticeUpdateVO) {
      return await updateNoticeById(notice);
    },
    async updateNoticeStatus(row: { announId: number; status: string }) {
      console.log('Updating notice status with data:', row);
      const announId = Number(row.announId);
      try {
        const { data: notice } = await this.getNoticeDetail(announId);
        console.log('Final request data for updateNoticeById:', {
          ...notice,
          status: row.status,
        });
        return await updateNoticeById({
          ...notice,
          status: row.status,
        });
      } catch (error) {
        const axiosError = error as AxiosError;
        console.error('Request data sent to updateNoticeById:', {
          announId,
          status: row.status,
        });
        console.error('Error response from server:', axiosError.response?.data || axiosError.message);
        throw error;
      }
    },
    async deleteNotice(announId: number) {
      try {
        return await deleteNoticeById(announId);
      } catch (error) {
        console.error('Error deleting notice:', error);
        throw error;
      }
    }
  }
});